package com.jxx.pda.pdaproject.activity;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jxx.pda.pdaproject.R;
import com.jxx.pda.pdaproject.bean.MifareClassCard;
import com.jxx.pda.pdaproject.bean.MifareSector;
import com.jxx.pda.pdaproject.util.Converter;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private NfcAdapter nfcAdapter = null;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private Intent nfcIntent;
    private TextView tv_cardinf;
    private Button btn_read;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        tv_cardinf = (TextView)findViewById(R.id.tv_cardinf);
        btn_read =(Button)findViewById(R.id.btn_read);
        btn_read.setOnClickListener(this);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if(nfcAdapter == null){
            Toast.makeText(MainActivity.this,"Device not support NFC",Toast.LENGTH_LONG).show();
            return;
        }else {
            if(!nfcAdapter.isEnabled()){
                Toast.makeText(MainActivity.this,"Your NFC not enable!",Toast.LENGTH_LONG).show();
                return;
            }
        }
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,getClass())
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[] { ndef, };
        mTechLists = new String[][] { new String[] { MifareClassic.class
                .getName() } };
    }

    @Override
    public void onNewIntent(Intent intent) {

        tv_cardinf.setText("");//清空显示
        //resolveIntent(intent);
        //获得封装NFC信息的intent
        nfcIntent = intent;
    }

    private void resolveIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)){
            Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            MifareClassic mfc = MifareClassic.get(tagFromIntent);
            String[] tagType = tagFromIntent.getTechList();
            for(int i = 0;i<tagType.length;i++){
                tv_cardinf.append(tagType[i]+"\r\n");
            }

            MifareClassCard mfiareClassCard = null;

            try {
                mfc.connect();
                boolean auth = false;
                int secCount = mfc.getSectorCount();
                tv_cardinf.append("Sector Count is"+secCount+"\r\n");
                mfiareClassCard = new MifareClassCard(secCount);
                int bCount=0;
                int bIndex =0;
                for(int i=0;i<secCount;i++){
                    tv_cardinf.append("****************\r\n");
                    MifareSector mifareSector = new MifareSector();
                    mifareSector.sectorIndex = i;
                    auth = mfc.authenticateSectorWithKeyA(i,MifareClassic.KEY_DEFAULT);
                    mifareSector.authorized = auth;
                    if(auth){
                        bCount = mfc.getBlockCount();
                        bCount = Math.min(bCount,MifareSector.BLOCKCOUNT);
                        tv_cardinf.append("Block Count is"+bCount+"\r\n");
                        bIndex = mfc.sectorToBlock(i);//返回扇区的第一个块的地址
                        tv_cardinf.append("bIndex is "+bIndex+"\r\n");
                        for(int j=bIndex;j<bIndex+bCount;j++){
                            byte[] blockfbytes = mfc.readBlock(j);
                            if(blockfbytes!=null){
                                tv_cardinf.append(Converter.getHexString(blockfbytes,blockfbytes.length)+"\r\n");
                                //tv_cardinf.append("Length is "+Converter.getHexString(blockfbytes,blockfbytes.length).length()/2+"\r\n");
                            }
                        }
                    }else{
                        tv_cardinf.append("Sector "+ i+" auth false!\r\n");
                    }
                }
                mfc.close();
            } catch (IOException e) {

            }finally {

            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
                mTechLists);
    }


    @Override
    public void onPause() {
        super.onPause();
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_read:{
                resolveIntent(nfcIntent);
                break;
            }
        }
    }
}
